<template>
    <view class="pg">
        <wd-form ref="form" :model="model">
            <wd-cell-group border>
                <wd-picker
                    required
                    value-key="id"
                    label-key="name"
                    size="large"
                    label="素材选择"
                    placeholder="请选择素材"
                    label-width="100px"
                    prop="mid"
                    v-model="model.mid"
                    :columns="materialList"
                    :rules="[{ required: true, message: '请选择素材' }]"
                />
                <wd-picker
                    required
                    value-key="id"
                    label-key="name"
                    size="large"
                    label="场地选择"
                    placeholder="请选择场地"
                    label-width="100px"
                    prop="rid"
                    v-model="model.rid"
                    :columns="regionList"
                    :rules="[{ required: true, message: '请选择场地' }]"
                />
                <wd-cell required title-width="190rpx" size="large" title="排序" custom-value-class="fl-ro-cen">
                    <template #default>
                        <wd-input-number :min="0" v-model="model.sort" />
                    </template>
                </wd-cell>
                <wd-picker
                    size="large"
                    label="类型选择"
                    placeholder="请选择类型"
                    label-width="100px"
                    prop="type"
                    v-model="model.type"
                    :columns="typeList"
                    :rules="[{ required: true, message: '请选择类型' }]"
                />
                <wd-cell title-width="190rpx" size="large" title="播放时长" prop="sort" custom-value-class="fl-ro-cen" :rules="[{ required: true, message: '请选择广告播放时长' }]">
                    <template #default>
                        <wd-input-number :min="3" v-model="model.duration" />
                    </template>
                </wd-cell>
                <wd-picker
                    size="large"
                    label="播放位置"
                    placeholder="请选择播放位置"
                    label-width="100px"
                    prop="type"
                    v-model="model.position"
                    :columns="positionList"
                    :rules="[{ required: true, message: '请选择播放位置' }]"
                />
                <title-block title="生效-截止日期" transparent></title-block>
                <wd-calendar
                    size="large"
                    label="生效日期"
                    v-model="model.effectTime"
                    :formatter="formatter"
                    prop="effectTime"
                    :rules="[{ required: true, message: '请选择生效日期' }]"
                />
                <wd-calendar
                    size="large"
                    label="截止日期"
                    v-model="model.cutoffTime"
                    :formatter="formatter"
                    prop="cutoffTime"
                    :rules="[{ required: true, message: '请选择截止日期' }]"
                />

                <wd-input
                    size="large"
                    label="申请说明"
                    label-width="100px"
                    clearable
                    v-model="model.remark"
                    prop="remark"
                    placeholder="请填写"
                    :maxlength="20"
                    show-word-limit
                    :rules="[{ required: true, message: '请填申请说明' }]"
                />
                <wd-button size="large" type="primary" custom-class="w-700 m-10-0-10-25" @click="handleSubmit">提交</wd-button>
            </wd-cell-group>
        </wd-form>
    </view>
</template>

<script setup>
    import { reactive, ref } from 'vue';
    import { onLoad } from '@dcloudio/uni-app';
    import { api_material_list } from '@/api/material.js';
    import { api_region_list } from '@/api/region.js';
    import { api_advertiseApply_save } from '@/api/advertiseApply.js';

    const form = ref(null); //表单
    // 模型数据
    const model = reactive({
        mid: '',
        rid: '',
        sort: '',
        type: '',
        duration: '',
        position: '',
        effectTime: null,
        cutoffTime: null,
        remark: ''
    });

    onLoad(async () => {
        try {
            //加载广告素材
            let res1 = await api_material_list({ pageCut: false });
            materialList.value = res1.data.map(({ id, name }) => ({ id, name })); //只保留id和name

            //加载广告素材
            let res2 = await api_region_list({ pageCut: false });
            regionList.value = res2.data.map(({ id, name }) => ({ id, name })); //只保留id和name
        } catch (error) {
            uni.showToast({
                title: '数据加载失败',
                icon: 'none'
            });
        }
    });

    // 类型选择器列表
    const materialList = ref([]);

    // 场地选择器列表
    const regionList = ref([]);

    // 类型选择器列表
    const typeList = ref([
        {
            value: 1,
            label: '安卓'
        },
        {
            value: 2,
            label: '小程序'
        }
    ]);

    //播放位置选择器列表
    const positionList = ref([
        {
            value: 1,
            label: '上半屏'
        },
        {
            value: 2,
            label: '下半屏'
        },
        {
            value: 3,
            label: '全屏'
        }
    ]);

    //日期选择器格式
    const formatter = (day) => {
        const date = new Date(day.date);
        const now = new Date();

        const year = date.getFullYear();
        const month = date.getMonth();
        const da = date.getDate();
        const nowYear = now.getFullYear();
        const nowMonth = now.getMonth();
        const nowDa = now.getDate();

        if (year === nowYear && month === nowMonth && da === nowDa) {
            day.topInfo = '今天';
        }

        if (month === 5 && da === 18) {
            day.topInfo = '618大促';
        }

        if (month === 10 && da === 11) {
            day.topInfo = '京东双11';
        }

        if (day.type === 'start') {
            day.bottomInfo = '开始';
        }

        if (day.type === 'end') {
            day.bottomInfo = '结束';
        }

        if (day.type === 'same') {
            day.bottomInfo = '开始/结束';
        }

        return day;
    };

    //时间戳转字符串
    const timestampToDateString = (timestamp) => {
        if (String(timestamp).length !== 13) {
            console.error('时间戳不是13位数字');
            return null;
        }
        let date = new Date(timestamp);
        let year = date.getFullYear();
        let month = String(date.getMonth() + 1).padStart(2, '0'); // 注意月份是从0开始的
        let day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    //获取当前 时:分
    /* const getCurrentTime = () => {
           // 创建一个新的Date对象，它会自动设置为当前日期和时间
           const now = new Date();

           // 从Date对象中获取小时（0-23）
           let hours = now.getHours();

           // 从Date对象中获取分钟（0-59）
           let minutes = now.getMinutes();

           // 如果小时或分钟是一位数，则在其前面补0
           hours = hours.toString().padStart(2, '0');
           minutes = minutes.toString().padStart(2, '0');

           // 返回格式化后的时间字符串
           return `${hours}:${minutes}`;
       };
    */
    // 提交表单
    const handleSubmit = async () => {
        // 执行表单验证
        try {
            let { valid, errors } = await form.value.validate();

            // 表单验证通过
            if (valid) {
                uni.showModal({
                    title: '是否提交',
                    success: async (res) => {
                        if (res.confirm) {
                            let param = { ...model, effectTime: timestampToDateString(model.effectTime), cutoffTime: timestampToDateString(model.cutoffTime) };
                            console.log(param);
                            // 访问添加接口;
                            try {
                                let res = await api_advertiseApply_save(param);
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'success',
                                    success: () => {
                                        uni.navigateBack();
                                    }
                                });
                            } catch (error) {
                                uni.showToast({
                                    title: error.msg,
                                    icon: 'none'
                                });
                            }
                        }
                    }
                });
            } else {
                console.log('校验失败', errors);
            }
        } catch (error) {
            // 表单验证失败或发生其他错误
            console.error('错误', error);
        }
    };
</script>

<style lang="scss" scoped>
    /* 你可以在这里添加样式 */
</style>
